package org.ruoyi.knowledge.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.ruoyi.common.core.domain.model.LoginUser;
import org.ruoyi.common.core.utils.MapstructUtils;
import org.ruoyi.common.core.utils.StringUtils;
import org.ruoyi.common.mybatis.core.page.PageQuery;
import org.ruoyi.common.mybatis.core.page.TableDataInfo;
import org.ruoyi.common.satoken.utils.LoginHelper;
import org.ruoyi.knowledge.domain.KnowledgeAttach;
import org.ruoyi.knowledge.domain.bo.KnowledgeAttachBo;
import org.ruoyi.knowledge.domain.vo.KnowledgeAttachVo;
import org.ruoyi.knowledge.domain.vo.KnowledgeInfoVo;
import org.ruoyi.knowledge.mapper.KnowledgeAttachMapper;
import org.ruoyi.knowledge.mapper.KnowledgeFragmentMapper;
import org.ruoyi.knowledge.mapper.KnowledgeInfoMapper;
import org.ruoyi.knowledge.service.IKnowledgeAttachService;
import org.ruoyi.knowledge.service.IKnowledgeInfoService;
import org.ruoyi.knowledge.service.RagflowService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 知识库附件Service业务层处理
 *
 * @author Lion Li
 * @date 2024-10-21
 */
@RequiredArgsConstructor
@Service
public class KnowledgeAttachServiceImpl implements IKnowledgeAttachService {

    private final KnowledgeAttachMapper baseMapper;

    private final KnowledgeFragmentMapper fragmentMapper;

    private final KnowledgeInfoMapper knowledgeInfoMapper;

    private final IKnowledgeInfoService knowledgeInfoService;

    private final RagflowService ragflowService;


    /**
     * 查询知识库附件
     */
    @Override
    public KnowledgeAttachVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询知识库附件列表
     */
    @Override
    public TableDataInfo<KnowledgeAttachVo> queryPageList(KnowledgeAttachBo bo, PageQuery pageQuery) {
        try {
            LambdaQueryWrapper<KnowledgeAttach> lqw = buildQueryWrapper(bo);
            Page<KnowledgeAttachVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
            
            // 增强数据：从RAGFlow获取解析状态和分块数
            if (result != null && result.getRecords() != null && !result.getRecords().isEmpty()) {
                enrichWithRagflowData(result.getRecords(), bo.getKid());
            }
            
            return TableDataInfo.build(result);
        } catch (Exception e) {
            System.err.println("查询知识库附件列表失败: " + e.getClass().getName() + " - " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
    
    /**
     * 从RAGFlow获取数据并填充到VO中
     */
    private void enrichWithRagflowData(List<KnowledgeAttachVo> attachList, String kid) {
        if (kid == null || attachList == null || attachList.isEmpty()) {
            return;
        }
        
        try {
            // 获取知识库信息
            List<KnowledgeInfoVo> knowledgeInfoList = knowledgeInfoMapper.selectVoByMap(Map.of("kid", kid));
            if (knowledgeInfoList == null || knowledgeInfoList.isEmpty()) {
                return;
            }
            
            KnowledgeInfoVo knowledgeInfo = knowledgeInfoList.get(0);
            String datasetId = knowledgeInfo.getRagflowDatasetId();
            if (datasetId == null || datasetId.isEmpty()) {
                return;
            }
            
            // 获取RAGFlow中的文档列表
            List<Map<String, Object>> ragflowDocuments = ragflowService.getDocuments(datasetId);
            if (ragflowDocuments == null || ragflowDocuments.isEmpty()) {
                return;
            }
            
            // 创建文档名到文档信息的映射
            Map<String, Map<String, Object>> docMap = ragflowDocuments.stream()
                .collect(Collectors.toMap(
                    doc -> (String) doc.get("name"),
                    doc -> doc,
                    (v1, v2) -> v1
                ));
            
            // 填充数据
            for (KnowledgeAttachVo attach : attachList) {
                Map<String, Object> ragflowDoc = docMap.get(attach.getDocName());
                if (ragflowDoc != null) {
                    // 设置默认启用状态：如果数据库中没有值或为0，则默认启用（1）
                    if (attach.getEnable() == null || attach.getEnable() == 0) {
                        attach.setEnable(1);
                    }
                    
                    // 设置分块数
                    Integer chunkCount = (Integer) ragflowDoc.get("chunk_count");
                    if (chunkCount != null) {
                        attach.setChunkCount(chunkCount);
                    }
                    
                    // 设置解析方法（parser_type）
                    String parserType = (String) ragflowDoc.get("parser_type");
                    if (parserType != null) {
                        attach.setParseMethod(parserType);
                    } else {
                        // 默认解析方法
                        attach.setParseMethod("general");
                    }
                    
                    // 设置解析状态和进度
                    String status = (String) ragflowDoc.get("status");
                    if (status != null) {
                        if ("parsing".equals(status)) {
                            attach.setParseProgress(50); // 解析中，设置50%进度
                            attach.setParseError(false);
                        } else if ("parsed".equals(status)) {
                            attach.setParseProgress(100); // 解析完成
                            attach.setParseError(false);
                        } else if ("error".equals(status) || "fail".equals(status)) {
                            attach.setParseProgress(0);
                            attach.setParseError(true);
                        } else {
                            // 其他状态，默认设置为解析中
                            attach.setParseProgress(50);
                            attach.setParseError(false);
                        }
                    } else {
                        // 没有状态信息，默认设置为解析完成
                        attach.setParseProgress(100);
                        attach.setParseError(false);
                    }
                } else {
                    // 如果RAGFlow中没有找到文档，设置默认值
                    if (attach.getEnable() == null || attach.getEnable() == 0) {
                        attach.setEnable(1);
                    }
                    attach.setChunkCount(0);
                    attach.setParseMethod("general");
                    // 如果没有在RAGFlow中找到，可能还在解析中或未上传
                    if (attach.getParseProgress() == null) {
                        attach.setParseProgress(0);
                    }
                }
            }
        } catch (Exception e) {
            // 如果获取RAGFlow数据失败，不影响主流程，只记录日志
            System.err.println("从RAGFlow获取文档信息失败: " + e.getMessage());
            // 设置默认值
            for (KnowledgeAttachVo attach : attachList) {
                if (attach.getEnable() == null || attach.getEnable() == 0) {
                    attach.setEnable(1);
                }
                if (attach.getChunkCount() == null) {
                    attach.setChunkCount(0);
                }
                if (attach.getParseMethod() == null) {
                    attach.setParseMethod("general");
                }
                if (attach.getParseProgress() == null) {
                    attach.setParseProgress(0);
                }
            }
        }
    }

    /**
     * 查询知识库附件列表
     */
    @Override
    public List<KnowledgeAttachVo> queryList(KnowledgeAttachBo bo) {
        LambdaQueryWrapper<KnowledgeAttach> lqw = buildQueryWrapper(bo);
        List<KnowledgeAttachVo> result = baseMapper.selectVoList(lqw);
        
        // 增强数据：从RAGFlow获取解析状态和分块数
        if (result != null && !result.isEmpty()) {
            enrichWithRagflowData(result, bo.getKid());
        }
        
        return result;
    }

    private LambdaQueryWrapper<KnowledgeAttach> buildQueryWrapper(KnowledgeAttachBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<KnowledgeAttach> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getKid()), KnowledgeAttach::getKid, bo.getKid());
        lqw.eq(StringUtils.isNotBlank(bo.getDocId()), KnowledgeAttach::getDocId, bo.getDocId());
        lqw.like(StringUtils.isNotBlank(bo.getDocName()), KnowledgeAttach::getDocName, bo.getDocName());
        lqw.eq(StringUtils.isNotBlank(bo.getDocType()), KnowledgeAttach::getDocType, bo.getDocType());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), KnowledgeAttach::getContent, bo.getContent());
        return lqw;
    }

    /**
     * 新增知识库附件
     */
    @Override
    public Boolean insertByBo(KnowledgeAttachBo bo) {
        KnowledgeAttach add = MapstructUtils.convert(bo, KnowledgeAttach.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改知识库附件
     */
    @Override
    public Boolean updateByBo(KnowledgeAttachBo bo) {
        KnowledgeAttach update = MapstructUtils.convert(bo, KnowledgeAttach.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(KnowledgeAttach entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除知识库附件
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void removeKnowledgeAttach(String docId) {
        Map<String,Object> map = new HashMap<>();
        map.put("doc_id",docId);
        baseMapper.deleteByMap(map);
        fragmentMapper.deleteByMap(map);
        
        // TODO: 需要实现Ragflow文档删除
        // 这里需要添加删除Ragflow中对应文档的逻辑
        // 但由于没有kid信息，暂时无法实现Ragflow同步删除
        System.err.println("注意: 本地删除后，Ragflow中的文档未删除");
    }
}
